package Leo.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * websocket 握手拦截器，检查握手请求和响应，对websockethandler传递属性，用于区别websocket
 */
public class BaseInterceptor extends HttpSessionHandshakeInterceptor{

    public final String SESSION_NAME = "sessionName";
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        System.out.println("开始握手");
        //获取session，并把uri中最后的参数作为名字写入到attributes中。我估计，此处执行后，底层会根据attributes和session创建Websocketsession。因为Websocket并没有继承HttpSession。
        String url = request.getURI().toString();
        String name = url.substring(url.lastIndexOf("/") + 1);
        attributes.put(SESSION_NAME,name);
        //看源代码可以发现，super的方法把session所有的属性都复制到attribute中了
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, @Nullable Exception ex) {
        System.out.println("握手之后");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
